package com.tanxi521.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.tanxi521.springboot.bean.*;
import com.tanxi521.springboot.pojo.*;
import com.tanxi521.springboot.service.OaUserService;
import com.tanxi521.springboot.service.PlayerAccountService;
import com.tanxi521.springboot.service.UserService;
import com.tanxi521.springboot.utils.DownLoadUtils;
import com.tanxi521.springboot.utils.HttpClientUtils;
import com.tanxi521.springboot.utils.SHA256Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: i-xiaotian
 * @Date: 2022/3/25 14:51
 * @EMAIL: 1254806967@qq.com
 */

@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(value = "用户", tags = "用户操作接口")
@Slf4j
public class UserController {

    @Resource
    private RedisTemplate<String, OaUser> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private OaUserService oaUserService;

    @Autowired
    private PlayerAccountService playerAccountService;

    @ApiOperation(value = "用户登录接口", notes = "用户是否注册", httpMethod = "POST")
    @PostMapping("/login")
    public APIResult login(@RequestBody OaUser oaUser) {
        String userName = oaUser.getUserName();
        PlayerAccount playerAccount = new PlayerAccount();
        playerAccount.setRealname(userName);
        PlayerAccount playerAccount1 = userService.queryPlayerAccount(playerAccount);
        if (playerAccount1 != null) {
            String password1 = playerAccount1.getPassword();
            String salt = password1.substring(5, 21);
            String inPass = "$SHA$" + salt + "$" + SHA256Util.getSHA256(oaUser.getPassword() + salt);
            if (!StringUtils.equals(playerAccount1.getPassword(), inPass)) {
                return new APIResult(APIResult.UN_CORRECT_PASSWORD, "账号或密码错误");
            } else {
                String token = UUID.randomUUID().toString().replace("-", "");
                OaUser isReg = userService.queryUser(oaUser);
                if (isReg != null) {
                    redisTemplate.opsForValue().set(token, isReg, 7, TimeUnit.DAYS);
                } else {
                    String uuid = userService.queryPlayerUuid(userName);
                    oaUser.setUserMcUuid(uuid);
                    oaUser.setUserRole(2);
                    oaUser.setGmtCreate(new Date());
                    oaUser.setGmtUpdate(new Date());
                    oaUser.setHeadImg("http://mc.tanxi521.com:9007/image/head_img/default_head" +
                            (new Random().nextInt(5) + 1) + ".png");
                    redisTemplate.opsForValue().set(token, oaUser, 7, TimeUnit.DAYS);
                    userService.insertNewUser(oaUser);
                }
                Token token1 = new Token(token);
                return new APIResult(token1, APIResult.SUCCESS, "登陆成功");
            }
        } else {
            return new APIResult(APIResult.UN_REG, "你还未注册，请先登陆游戏");
        }
    }

    @PostMapping("/password")
    @RestPoint
    public APIResult changePassword(@RequestBody ChangePasswordOBJ changePasswordOBJ, HttpServletRequest request){
        String oldPwd = changePasswordOBJ.getOldPwd();
        String newPwd = changePasswordOBJ.getNewPwd();
        String token = request.getHeader("X-Token");
        OaUser oa_user = (OaUser)redisTemplate.opsForValue().get(token);
        String userName = oa_user.getUserName();
        PlayerAccount playerAccount = new PlayerAccount();
        playerAccount.setRealname(userName);
        playerAccount = userService.queryPlayerAccount(playerAccount);
        if (playerAccount != null) {
            String password = playerAccount.getPassword();
            String salt = password.substring(5, 21);
            String inPass = "$SHA$" + salt + "$" + SHA256Util.getSHA256(oldPwd + salt);
            if (!inPass.equals(password)) {
                return new APIResult(APIResult.FAIL, "原密码错误，修改密码失败");
            }
            newPwd = "$SHA$" + salt + "$" + SHA256Util.getSHA256(newPwd + salt);
            int i = userService.updateUserPwd(userName, newPwd);
            if (i != 0) {
                return new APIResult(APIResult.SUCCESS, "密码修改成功，请重新登录");
            }
        }
        return new APIResult(APIResult.FAIL, "操作失败，请重试");
    }

    @PostMapping("/logOut")
    @RestPoint
    public APIResult logOut(HttpServletRequest request) {
        String token = request.getHeader("X-Token");
        redisTemplate.opsForValue().set(token, new OaUser(), 1, TimeUnit.MILLISECONDS);
        return new APIResult(APIResult.SUCCESS, "success");
    }

    @GetMapping("/info")
    public APIResult getUserInfo(String token) {
        Object oaUser = redisTemplate.opsForValue().get(token);
        if (oaUser != null) {
            LoginResult loginResult = userService.queryUserInfo((OaUser) oaUser);
            LoginBean loginBean = new LoginBean();
            String[] roles = new String[1];
            roles[0] = loginResult.getRole();
            loginBean.setRoles(roles);
            loginBean.setAvatar(loginResult.getAvatar());
            loginBean.setName(loginResult.getName());
            return new APIResult(loginBean, APIResult.SUCCESS, "查询用户信息成功");
        } else {
            return new APIResult(APIResult.UN_LOGIN, "未登录或登录已过期");
        }
    }

    @GetMapping("/detail")
    @RestPoint
    public APIResult getUserDetail(String name) {
        PlayerInfoCard playerInfoCard = null;
        try {
            playerInfoCard = userService.queryUserDetail(name);
        } catch (MyBatisSystemException e) {
            return new APIResult(APIResult.FAIL, "系统繁忙，请稍后再试");
        }
        if (playerInfoCard == null) {
            return new APIResult(APIResult.FAIL, "该用户不存在");
        }
        if (playerInfoCard.getVip() != null) {
            if (playerInfoCard.getDuration() == -1) {
                playerInfoCard.setVipTime("永久");
            } else if (Long.parseLong(playerInfoCard.getVipTime()) < 0) {
                playerInfoCard.setVipTime("已过期");
            } else {
                playerInfoCard.setVipTime(playerInfoCard.getVipTime() + " 天");
            }
        } else {
            playerInfoCard.setVip("无");
            playerInfoCard.setVipTime("无");
        }
        if (playerInfoCard.getPoints() == null) {
            playerInfoCard.setPoints(0);
        }
        if (playerInfoCard.getAfkTime() != null){
            String afkTime = playerInfoCard.getAfkTime();
            Long afkTimeL = Long.parseLong(afkTime)/1000;
            Long h = afkTimeL / 3600;
            Long m = (afkTimeL - h * 3600) / 60;
            Long s = (afkTimeL - h * 3600) % 60;
            playerInfoCard.setAfkTime(h + "时" + m + "分" + s + "秒");
        } else {
            playerInfoCard.setAfkTime("没有挂机过");
        }
        return new APIResult(playerInfoCard, APIResult.SUCCESS, "查询用户信息成功");
    }

    @GetMapping("/userList")
    @RestPoint
    public APIResult getUserList(Integer pageSize, Integer pageIndex, String userName, Integer isLogged) {
        AllPlayerInfoCardInfo allPlayerInfoCards = new AllPlayerInfoCardInfo();
        allPlayerInfoCards.setUserName(userName);
        allPlayerInfoCards.setIsLogged(isLogged);
        List<AllPlayerInfoCardInfo> allPlayerInfoCardInfos = userService.queryAllPlayerInfoCard(pageSize, pageIndex, allPlayerInfoCards);
        int count = userService.queryUserCountByMc(allPlayerInfoCards);
        for (AllPlayerInfoCardInfo allPlayerInfoCardInfo : allPlayerInfoCardInfos) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String regTime = allPlayerInfoCardInfo.getRegTime();
            String lastLoginTime = allPlayerInfoCardInfo.getLastLoginTime();
            allPlayerInfoCardInfo.setRegTime(sdf.format(new Date(Long.parseLong(regTime))));
            allPlayerInfoCardInfo.setLastLoginTime(sdf.format(new Date(Long.parseLong(lastLoginTime))));
            if (allPlayerInfoCardInfo.getHead_img() == null) {
                allPlayerInfoCardInfo.setHead_img("网页未登录");
            }
        }
        AllPlayerInfoCard allPlayerInfoCard = new AllPlayerInfoCard();
        allPlayerInfoCard.setAllPlayerInfoCardInfos(allPlayerInfoCardInfos);
        allPlayerInfoCard.setPlayerCount(count);
        allPlayerInfoCard.setPageCount(count / pageSize + 1);
        return new APIResult(allPlayerInfoCard, APIResult.SUCCESS, "获取所有玩家信息成功");
    }

    @GetMapping("/skinUrl")
    @RestPoint
    public APIResult getUserSkin(String name){
        String getPlayerUUID = "https://api.mojang.com/users/profiles/minecraft/" + name;
        String playerUUIDResult = null;
        String url = null;
        try {
            playerUUIDResult = HttpClientUtils.doGet(getPlayerUUID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.equals("", playerUUIDResult)) {
            JSONObject jsonObject = JSONObject.parseObject(playerUUIDResult);
            String uuid = jsonObject.getString("id");
            String getPlayerSkinInfo = "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid;
            String playerSkinResult = null;
            try {
                playerSkinResult = HttpClientUtils.doGet(getPlayerSkinInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject jsonObject1 = JSONObject.parseObject(playerSkinResult);
            String properties = jsonObject1.getString("properties");
            String substring = properties.substring(properties.indexOf("[") + 1, properties.indexOf("]"));
            JSONObject skinValue = JSONObject.parseObject(substring);
            String value = skinValue.getString("value");
            byte[] decode = Base64.getDecoder().decode(value);
            String playerSkinValue = new String(decode);
            JSONObject jsonObject2 = JSONObject.parseObject(playerSkinValue);
            String string = jsonObject2.getString("textures");
            JSONObject skinUrlBefore = JSONObject.parseObject(string);
            String skin = skinUrlBefore.getString("SKIN");
            JSONObject skinUrl = JSONObject.parseObject(skin);
            url = skinUrl.getString("url");
            try {
//                DownLoadUtils.download(url, name, "D:\\0日常录屏以及截图");
                DownLoadUtils.download(url, name, "D:\\MC服务器\\web\\tn_admin\\skin");
                url = "http://mc.tanxi521.com:9007/image/skin/" + name + ".png";
                log.info("用户 " + name + " 皮肤保存成功");
            } catch (Exception e) {
                url = "http://mc.tanxi521.com:9007/image/skin/default.png";
            }
        } else {
            url = "http://mc.tanxi521.com:9007/image/skin/default.png";
        }
        return new APIResult(url, APIResult.SUCCESS, "图片地址返回");
    }

    @PostMapping("/edit")
    @RestPoint
    @OpNeed
    public APIResult editUser(@RequestBody EditUserInfoBean editUserInfoBean, HttpServletRequest request) {
        String token = request.getHeader("X-Token");
        OaUser oa_user = (OaUser)redisTemplate.opsForValue().get(token);
        if (oa_user.getUserRole() != 1) {
            log.warn(oa_user.getUserName() + " 尝试无权限修改");
            return new APIResult(APIResult.FAIL, "你莫得权限");
        }
        APIResult apiResult = null;
        try {
            log.info(oa_user.getUserName() + " 编辑了 " + editUserInfoBean.getName() + " 的信息");
            apiResult = playerAccountService.updateUserInfo(editUserInfoBean);
        } catch (Exception e) {
            return new APIResult(APIResult.FAIL, "未知错误，请重试");
        }
        return apiResult;
    }

    @PostMapping("/headImg")
    @RestPoint
    public APIResult changeHeadImg(@RequestBody OaUser oaUser, HttpServletRequest request) {
        String imgUrl = oaUser.getHeadImg();
        String token = request.getHeader("X-Token");
        OaUser oa_user = (OaUser)redisTemplate.opsForValue().get(token);
        oa_user.setHeadImg(imgUrl);
        redisTemplate.opsForValue().set(token, oa_user, 7, TimeUnit.DAYS);
        int i = userService.updateUserHeadImg(oa_user);
        if (i != 0) {
            return new APIResult(imgUrl, APIResult.SUCCESS, "头像修改成功");
        } else {
            return new APIResult(APIResult.FAIL, "修改头像失败，请重试");
        }
    }

}
